var myNode = new MyNode(); 		// 현재 노드 정보를 저장하는 객체 
var isFirst = true; 			// 첫 노드를 보여줄때는 애니메이션 사용하지않음
var DB = null; 					// 계속 DB를 열고 닫지 않기 위해 전역변수로 할당.
var isMoveDeny = false; 		// 화면 전환중에는 moveNode 메소드를 실행 하지않음.
var isBgAudioPlay = false;		// 앱의 배경음악(Pause/Play 하기위한 상태)
var bg_media = null; 			// 배경음악 객체
var bgAudioInterval = null;		// 반복 제어를 위해 사용하는 객체
var DurationTIME = 0;			// 화면 전환 시간(ms)			
var aniCount = 0;				// 템플릿내부 애니메이션 프레임수
var aniInterval = null;			// 템플릿내부 애니메이션 갱신시간 객체
var isWeb = false;				// 디바이스인지 WebPreview인지 구분

function MyNode(){
    var me = this;
    var nowNode = 0; // 현재 노드 시작값으로 0
    var childProduct = null; // 자식 product가 들어가는 자리
    var childNode = null;
    var myResouce = null;
    var nodeNum = null;
    var productNum = null;
    var resouceNum = null;
    var contentInnerHtmlTpl = null;
    this.setResourceArray = function(len){
        me.myResource = new Array(len);
    }
    this.setChildProductArray = function(len){
        me.childProduct = new Array(len);
    }
    this.setChildNodeArray = function(len){
        me.childNode = new Array(len);
    }
}

function tplStart(){

    LOG("OPEN TPL : TPL.html");
	Ext.getBody().unmask();
    document.ontouchmove = function(event){
        event.preventDefault();
    };
    if (navigator.userAgent.match(/iPad/) == null && navigator.userAgent.match(/iPhone|Mobile|UP.Browser|Android|BlackBerry|Windows CE|Nokia|webOS|Opera Mini|SonyEricsson|opera mobi|Windows Phone|IEMobile|POLARIS/) != null) {
        document.addEventListener("backbutton", onBackKeyDown, false);
    }
    else {
        Sound_ON = false;
		isWeb = true;
    }
	
    DB = window.openDatabase("Database", "0.1", "Pub-Client Demo", 5 * 1024 * 1024);
    moveNode(0, "xtpl01", true, 'fade');
}


function moveNode(nodeID, tplname, reverseTF, animType){
    LOG("[moveNode] ")
	if(DefaultPageANIM != ''){
		animType = DefaultPageANIM;
	}
	if(isWeb){
		animType = WebPageANIM;
	}
	if (booster){
		animType = BoostPageANIM;
		tplAnimaton = false;
	}
    switch (animType) {
        case 'pop':
            DurationTIME = 1000;
            break;
        case 'slide':
            DurationTIME = 1000;
            break;
        case 'fade':
            DurationTIME = 500;
            break;
        case 'cube':
            DurationTIME = 1000;
            break;
        case 'flip':
            DurationTIME = 1500;
            break;
    }
    if (!isMoveDeny) {
        moveDeny();
        moveAudio()
        if (!isFirst) {
            Ext.getCmp('TempPanel').el.setStyle({
                backgroundImage: 'url(' + myNode.bgimage + ')'
            })
        }
        if (!booster) {
            if (myNode.contentInnerHtmlTpl != null) {
                Ext.getCmp("TempPanel").tpl = myNode.contentInnerHtmlTpl;
                Ext.getCmp("TempPanel").update(myNode);
            }
        }
        myNode.nowNode = nodeID;
        updateTPL(tplname, reverseTF, animType);
    }
}

function tempPanelSetup(bg){
    Ext.getCmp('TempPanel').el.setStyle({
        backgroundImage: 'url(' + path.pre + bg + ')'
    })
}

function onBackKeyDown(){
    alertAudio();
    Ext.Msg.confirm("알림", "종료하시겠습니까?", function(buttonId){
        if (buttonId == "yes") {
            navigator.app.exitApp();
        }
        else {
        }
    })
}

function updateTPL(tplName, reverseTF, animType){
    LOG("[updateTPL]")
    Ext.Ajax.request({
        url: path.tpl + tplName + '.tpl',
        failure: function(response, options){
            if (confirm('파일을 찾을수 없습니다. \n 프로그램을 종료합니다.')) {
                navigator.app.exitApp();
            }
            else {
            }
        },
        success: function(response, options){
            var contentInnerHtmlTpl = new Ext.XTemplate(response.responseText);
            LOG("Update InnerHtmlTpl");
            myNode.contentInnerHtmlTpl = contentInnerHtmlTpl;
            Ext.getCmp("MainPanel").tpl = contentInnerHtmlTpl;
        },
        callback: function(opts, isSuccess, response){
            getMyNode(myNode, reverseTF, animType);
            getMyChlid(myNode);
        }
    });
    
}


function getMyNode(myNode, reverseTF, animType){
    LOG("[getMyNode] : " + myNode.nowNode)
    var sql = "select * from Client_Node where node_id==" + myNode.nowNode + ""
    DB.transaction(function(tx){
        tx.executeSql(sql, [], function(tx, results){
            var len = results.rows.length;
            if (len == 1) {
                myNode.nodeNum = results.rows.item(0).nodeNum;
                myNode.productNum = results.rows.item(0).productNum;
                return getMyResource(myNode, reverseTF, animType);
            }
            else {
                LOG("현재 Node 정보(Client_Node 테이블)에 이상이 있습니다.")
            }
        }, function(err){
            XLOG("executeSql ERR(getMyResource)  ERROR CODE:[" + err.text + "]");
        });
    }, function(err){
        XLOG("transaction ERR(getMyResource) ERROR CODE:[" + err.text + "]");
    });
}

function getMyResource(myNode, reverseTF, animType){
    LOG("[getMyResource]")
    var sql = "select * from Client_ResourceMap where parent_id=='" + myNode.nowNode + "'"
    DB.transaction(function(tx){
        tx.executeSql(sql, [], function(tx, results){
            var len = results.rows.length;
            myNode.setResourceArray(len);
            
            for (var i = 0; i < len; i++) {
                myNode.myResource[i] = results.rows.item(i)
                if (results.rows.item(i).type == "bgimage") {
                    myNode.bgimage = results.rows.item(i).path;
                    Ext.getCmp('MainPanel').el.setStyle({
                        backgroundImage: 'url(' + myNode.bgimage + ')'
                    })
                }
            }
            return updatePanel(myNode, reverseTF, animType);
        }, function(err){
            XLOG("executeSql ERR(getMyResource)  ERROR CODE:[" + err.text + "]");
        });
    }, function(err){
        XLOG("transaction ERR(getMyResource) ERROR CODE:[" + err.text + "]");
    });
}

function countNode(){
    var count = -1;
    return function(){
        return (count += 1)
    }
}

function countProduct(){
    var count = -1;
    return function(){
        return (count += 1)
    }
}


function getMyChlid(myNode){
    var sql = "select * from Client_ChildMap where node_id=='" + myNode.nowNode + "'";
    LOG("[getMyChlid]")
    DB.transaction(function(tx){
        tx.executeSql(sql, [], function(tx, results){
            var childLen = results.rows.length;
            myNode.setChildProductArray(myNode.productNum);
            myNode.setChildNodeArray(myNode.nodeNum);
            var productNum = countProduct();
            var nodeNum = countNode();
            for (var i = 0; i < childLen; i++) {
                if (results.rows.item(i).child_type == "product") {
                    myNode.childProduct[productNum()] = results.rows.item(i);
                }
                else 
                    if (results.rows.item(i).child_type == "node") {
                        myNode.childNode[nodeNum()] = results.rows.item(i);
                    }
            }
            /* Debug Code 
            LOG("-----------------DEBUG")
            for (var j = 0; j < myNode.childProduct.length; j++) {
                LOG("myNode.childProduct[" + j + "] : " + myNode.childProduct[j].icon)
            }
            for (var j = 0; j < myNode.childNode.length; j++) {
                LOG("myNode.childNode[" + j + "] : " + myNode.childNode[j].icon)
            }
            //*/
        }, function(err){
            XLOG("executeSql ERR(getMyChlid)  ERROR CODE:[" + err.code + "]");
        });
    }, function(err){
        XLOG("transaction ERR(getMyChlid) ERROR CODE:[" + err.code + "]");
    });
}


function updatePanel(myNode, reverseTF, animType){
    LOG("[updatePanel]")
    Ext.getCmp("MainPanel").update(myNode);
    
    if (isFirst == true) {
        /*
         Ext.getCmp("RootPanel").setActiveItem(0, {
         type: StartANIM,
         duration: 1000,
         })*/
        LOG("FirstPAGE")
        ///		Ext.getCmp("RootPanel").setActiveItem(1);
        Ext.getCmp("RootPanel").setActiveItem(0);
        playBgAudio();
        isFirst = false;
        moveAllow()
    }
    else {
        moveAllow();
        animStoper();
        Ext.getCmp("RootPanel").setActiveItem(1);
        Ext.getCmp("RootPanel").setActiveItem(0, {
            type: animType,
            duration: DurationTIME,
            reverse: !reverseTF
        });
    }
}

function moveDeny(){
    isMoveDeny = true;
}

function moveAllow(){
    setTimeout("isMoveDeny=false;LOG('isMoveDeny:false')", DurationTIME)
}

/** [상품페이지 오버레이] *****************************************************************************************/


function payPage(){
    Ext.Msg.confirm("결제", "구매하시겠습니까?", function(buttonId){
        if (buttonId == "yes") {
            Ext.Msg.alert("결제2", "결제페이지로 이동합니다.")
        }
        else {
        
        }
    })
}

function overlayShow(productID,productTplName){
	Ext.Ajax.request({
        url: path.tpl + productTplName + '.tpl',
        failure: function(response, options){
			LOG("productTpl:"+ path.tpl + productTplName + '.tpl')
            if (confirm('상품 템플릿 파일을 찾을수 없습니다. \n 프로그램을 종료합니다.')) {
				
                navigator.app.exitApp();
            }
            else {
            }
        },
        success: function(response, options){
            var productInnerHtmlTpl = new Ext.XTemplate(response.responseText);
            LOG("Update Product InnerHtmlTpl");
            Ext.getCmp("ProductPage").tpl = productInnerHtmlTpl;
        },
        callback: function(opts, isSuccess, response){
            getProductInfoSQL(productID)
        }
    });
    
}

function getProductInfoSQL(productID,productTplName){
    var sql = 'select *  from Client_Product  where product_id==' + productID + '';
    DB.transaction(function(tx){
        tx.executeSql(sql, [], function(tx, results){
            var len = results.rows.length;
            if (len == 1) {
                var productInfo = results.rows.item(0);
                return getMyProductResource(productInfo)
            }
        }, function(err){
            XLOG("executeSql ERR(getMyResource)  ERROR CODE:[" + err.text + "]");
        });
    }, function(err){
        XLOG("transaction ERR(getMyResource) ERROR CODE:[" + err.text + "]");
    });
}




function getMyProductResource(productInfo){
    LOG("[getMyResource]")
    var sql = "select * from Client_ResourceMap where parent_id=='" + productInfo.product_id + "'"
    DB.transaction(function(tx){
        tx.executeSql(sql, [], function(tx, results){
            var len = results.rows.length;
            productInfo.resource = new Array(len);
            for (var i = 0; i < len; i++) {
                productInfo.resource[i] = results.rows.item(i)
                if (results.rows.item(i).type == "bgimage") {
                    productInfo.bgimage = results.rows.item(i).path;
					productInfo.resource = results.rows.item(i);
                    LOG("backgroundImage:" + productInfo.bgimage )
                }
            }
            return showCenteredOverlay(productInfo);
        }, function(err){
            XLOG("executeSql ERR(getMyResource)  ERROR CODE:[" + err.text + "]");
        });
    }, function(err){
        XLOG("transaction ERR(getMyResource) ERROR CODE:[" + err.text + "]");
    });
}


function showCenteredOverlay(productInfo){
	Ext.getCmp("ProductPage").update(productInfo);
    Ext.getCmp("ProductPage").setCentered(true);
    Ext.getCmp("ProductPage").show();
    alertAudio();
};




/**[ SOUND_PLAY ]**************************************************************************/
function alertAudio(){
    if (Sound_ON == true) {
		LOG("PLAY "+ path.snd.alert)
        new Media(path.snd.alert, function(){
            this.release()
        }).play();
    }
}

function moveAudio(){
    if (Sound_ON == true) {
		LOG("PLAY "+ path.snd.nextpage)
        new Media(path.snd.nextpage, function(){
            this.release()
        }).play();
    }
}


function playBgAudio(){
    if (Sound_ON == true) {
        if (isBgAudioPlay == false) {
            isBgAudioPlay = true;
            LOG("[isBgAudioPlay] : false")
            if (!bg_media) {
                LOG("[Create bg_media] : " + path.snd.bgm)
                bg_media = new Media(path.snd.bgm, function(){
                    bg_media.release();
                    isBgAudioPlay = false;
                    LOG("[playBgAudio]")
                }, function(err){
                    LOG("playBgAudio():Audio Error: " + err.message);
                    isBgAudioPlay = false;
                }, function(status){
                    if (status == 4) {
                        LOG("[REPLAY BGSong]")
                        playBgAudio();
                    }
                });
            }
            bg_media.play();
        }
    }
}

function stopBgAudio(){
    if (isBgAudioPlay) {
        isBgAudioPlay = false;
        bg_media.pause();
        //bg_media.release();
    }
    else {
        //isBgAudioPlay = true;
        //bg_media.play();
        playBgAudio();
    }
}


/**[ ANIMATION ]**************************************************************************/
function animStarter(id, aniPath, maxFrame){
    LOG("animStarter : " + Ext.getCmp("RootPanel").getActiveItem().id)
    if (tplAnimaton == true) {
        animStoper();
        if (Ext.getCmp("RootPanel").getActiveItem().id == "MainPanel") {
            return animSet(id, aniPath, maxFrame)
        }
        else {
            animStoper();
        }
    }
}

function animSet(id, aniPath, maxFrame){
    LOG("[animSet]")
    aniInterval = setInterval("animator('" + id + "','" + aniPath + "'," + maxFrame + ")", 50)
}

function animator(id, aniPath, maxFrame){
    //LOG("[animator]")
    tempnum = AniCounter(maxFrame);
    document.getElementById(id).src = (aniPath + tempnum + ".png")
}

function AniCounter(maxFrame){
    if (aniCount == maxFrame) {
        aniCount = 0;
    }
    else {
        aniCount = aniCount + 1;
    }
    return aniCount;
}

function animStoper(){
    LOG("ANI STOP")
    clearInterval(aniInterval);
}

/****************************************************************************/

function panelMaker(){
    LOG("[panelMaker]")
    tempPanel = new Ext.Panel({
        id: 'TempPanel',
        style: "background-position:center center;",
        fullscreen: true,
    })
    mainPanel = new Ext.Panel({
        id: 'MainPanel',
        fullscreen: true,
        style: "background-position:center center;",
        tpl: new Ext.XTemplate()
    })
    rootPanel = new Ext.Panel({
        id: 'RootPanel',
        fullscreen: true,
        layout: 'card',
        items: [mainPanel, tempPanel]
    })
    
    new Ext.Panel({
		id: "ProductPage",
		floating: true,
		modal: true,
		width: 640,
		opacity: "1",
		height: 480,
		tpl: new Ext.XTemplate(),
		config: {
			layout: 'fit',
			style: 'border-radius:0px;		opacity: 0.75;		font-size: small;',
			height: '100%',
		}
	}
    )
    
    Ext.getCmp('RootPanel').el.setStyle({
        backgroundImage: "url('BG00.png')"
    })
	Ext.getCmp('TempPanel').el.setStyle({
        backgroundImage: "url('BG00.png')"
    })
    Ext.getCmp('MainPanel').el.setStyle({
        backgroundImage: "url('BG00.png')"
    })

}

